package com.jianganming.netty.heartbeat;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;

import java.util.concurrent.TimeUnit;

/**
 * 心跳检测服务
 */
public class HeartBeatServer {

    public static void main(String[] args) {
        EventLoopGroup group1 = new NioEventLoopGroup(1);
        EventLoopGroup group2 = new NioEventLoopGroup();
        ServerBootstrap bootstrap = new ServerBootstrap();
        try{
            ChannelFuture future = bootstrap.group(group1, group2)
                    .channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.INFO))//添加日志处理器
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            //readerIdleTime 3秒没有读到，发起一次心跳检测
                            //writerIdleTime 5秒没有写，发起一次心跳检测
                            //allIdleTime 7秒没有读到和写，发起一次心跳检测
                            pipeline.addLast(new IdleStateHandler(3, 5, 7, TimeUnit.SECONDS));
                            pipeline.addLast(new HeartBeatHandler());
                        }
                    }).bind(8889).sync();
            future.channel().closeFuture().sync();
        }catch (Exception e){

        }finally {
            group1.shutdownGracefully();
            group2.shutdownGracefully();
        }
    }
}

class HeartBeatHandler extends ChannelInboundHandlerAdapter{
    private static InternalLogger logger = InternalLoggerFactory.getInstance(HeartBeatHandler.class);
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {

        if(evt instanceof IdleStateEvent){
            IdleStateEvent stateEvent = (IdleStateEvent) evt;
            switch (stateEvent.state()){
                case READER_IDLE:
                    logger.info(ctx.channel().remoteAddress()+":读空闲");
                    break;
                case WRITER_IDLE:
                    logger.info(ctx.channel().remoteAddress()+":写空闲");
                    break;
                case ALL_IDLE:
                    logger.info(ctx.channel().remoteAddress()+":读写空闲");
                    break;
            }
        }
        logger.info("服务器做相应处理");
    }
}
